<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
<!--        <div class="handle-box">-->
          <el-button type="primary" icon="el-icon-refresh" @click="getList" class="mr20">刷新</el-button>
          <el-button type="primary" @click="handleGenerate">生成大码</el-button>

<!--        </div>-->
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="small"
        class="mt25"
      >
        <el-table-column
          prop="id"
          label="ID"
          min-width="60"
        />
        <el-table-column
          prop="file_name"
          label="大码文件名"
          min-width="180"
        />
        <el-table-column
          prop="number"
          label="数量"
          min-width="80"
        />
        <el-table-column
          prop="mark"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="add_time"
          label="创建时间"
          min-width="180"
        />
        <el-table-column
          label="操作"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="handleDownload(scope.row.id)"
              :loading="scope.row.downloading"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 50]"
          :page-size="searchForm.limit"
          :current-page="searchForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    
    <!-- 生成大码弹窗 -->
    <el-dialog
      title="生成大码"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form
        ref="generateForm"
        :model="generateForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="生成数量" prop="number">
          <el-input 
            v-model.number="generateForm.number" 
            placeholder="请输入生成数量(最大输入5000)"
            style="width: 100%"
            @input="validateNumberInput"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="mark">
          <el-input 
            v-model="generateForm.mark" 
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGenerate" :loading="submitLoading">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getBigCodeList, createBigCode, getBigCodeUrl } from '@/api/seed';
import { mapState } from 'vuex';

export default {
  name: 'BigCodeIndex',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        code: '',
        status: ''
      },
      listLoading: false,
      tableData: {
        data: [],
        total: 0
      },
      dialogVisible: false,
      submitLoading: false,
      generateForm: {
        number: null,
        mark: ''
      },
      rules: {
        number: [
          { required: true, message: '请输入生成数量', trigger: 'blur' },
          { type: 'number', min: 1, max: 5000, message: '数量范围在1-5000之间', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapState('app', ['pageLimit'])
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取大码列表
    getList() {
      this.listLoading = true;
      getBigCodeList(this.searchForm)
        .then(res => {
          if (res.status === 200) {
            this.tableData.data = res.data.list || [];
            this.tableData.total = res.data.count || 0;
            // 添加下载状态标记
            this.tableData.data.forEach(item => {
              this.$set(item, 'downloading', false);
            });
          } else {
            this.$message.error(res.msg || '获取数据失败');
          }
        })
        .catch(err => {
          this.$message.error(err.msg || '获取数据失败');
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    
    // 切换分页
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    
    // 切换每页显示条数
    handleSizeChange(val) {
      this.searchForm.limit = val;
      this.getList();
    },
    
    // 打开生成大码弹窗
    handleGenerate() {
      this.dialogVisible = true;
      this.generateForm.number = null;
      this.generateForm.mark = '';
    },
    
    // 提交生成大码
    submitGenerate() {
      this.$refs.generateForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          createBigCode(this.generateForm)
            .then(res => {
              if (res.status === 200) {
                this.$message.success(`成功生成${this.generateForm.number}个大码`);
                this.dialogVisible = false;
                this.getList(); // 刷新列表
              } else {
                this.$message.error(res.msg || '生成失败');
              }
            })
            .catch(err => {
              this.$message.error(err.msg || '生成失败');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      });
    },

    // 下载大码文件
    handleDownload(id) {
      const row = this.tableData.data.find(item => item.id === id);
      if (row) {
        row.downloading = true;
        getBigCodeUrl(id)
          .then(res => {
            if (res.status === 200 && res.data.file) {
            //   // 创建一个隐藏的a标签用于下载
            //   const link = document.createElement('a');
            //   link.href = res.data.file;
            //   link.download = row.file_name + '.txt';
            //   document.body.appendChild(link);
            //   link.click();
            //   document.body.removeChild(link);
            //   this.$message.success('下载成功');
              this.downloadFile(res.data.file);
            //   this.downloadFile(res.data.file);
            } else {
              this.$message.error(res.msg || '获取下载链接失败');
            }
          })
          .catch(err => {
            this.$message.error(err.meg || '下载失败');
          })
          .finally(() => {
            row.downloading = false;
          });
      }
    },
    downloadFile(url) {
      if (!url) {
        this.$message.error('下载地址不存在');
        return;
      }


      // 创建一个隐藏的a标签来下载文件
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.style.display = 'none';

      // 从URL中提取文件名
      const filename = url.substring(url.lastIndexOf('/') + 1);
      link.download = filename;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 验证数量输入
    validateNumberInput(val) {
      // 如果输入为空，保持为空
      if (val === '' || val === null || val === undefined) {
        this.generateForm.number = null;
        return;
      }

      // 移除非数字字符
      val = val.toString().replace(/[^\d]/g, '');

      // 如果处理后为空，设为null
      if (val === '') {
        this.generateForm.number = null;
        return;
      }

      // 转为数字并验证范围
      let num = Number(val);

      if (num > 5000) {
        num = 5000;
        this.$message.warning('最大输入数量不能超过5000');
      } else if (num < 1) {
        num = 1;
        this.$message.warning('最小输入数量不能小于1');
      }

      // 更新值
      this.generateForm.number = num;
    },
  }
};
</script>

<style scoped lang="scss">
.handle-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.input-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.mr20 {
  margin-right: 20px;
  margin-bottom: 10px;
}

.mt25 {
  margin-top: 25px;
}

.block {
  margin-top: 20px;
  text-align: right;
}

.input-with-select {
  width: 300px;
}

// 确保输入框的宽度和样式
::v-deep .el-input {
  width: 100% !important;
  
  .el-input__inner {
    width: 100% !important;
  }
}
</style> 